package com.core.tag.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.core.util.DspUtil;
import com.dsp.bean.SelectTag;
import com.dsp.services.SelectTagService;

public class RadioTag extends TagSupport {

	Logger logger = Logger.getLogger(DspUtil.Log4J);

	/**
	 * 
	 */
	private static final long serialVersionUID = -6426856539331047426L;

	/**
	 * 标签名称
	 */
	private String tagId;
	/**
	 * 页面显示名称
	 */
	private String htmlId;
	/**
	 * 数据库值
	 */
	private String htmlValue;

	/**
	 * 事件
	 */
	private String oAction;

	/**
	 * @return the tagId
	 */
	public String getTagId() {
		return tagId;
	}

	/**
	 * @return the htmlId
	 */
	public String getHtmlId() {
		return htmlId;
	}

	/**
	 * @return the htmlValue
	 */
	public String getHtmlValue() {
		return htmlValue;
	}

	/**
	 * @param tagId
	 *            the tagId to set
	 */
	public void setTagId(String tagId) {
		this.tagId = tagId;
	}

	/**
	 * @param htmlId
	 *            the htmlId to set
	 */
	public void setHtmlId(String htmlId) {
		this.htmlId = htmlId;
	}

	/**
	 * @param htmlValue
	 *            the htmlValue to set
	 */
	public void setHtmlValue(String htmlValue) {
		this.htmlValue = htmlValue;
	}

	/**
	 * @return the oAction
	 */
	public String getoAction() {
		return oAction;
	}

	/**
	 * @param oAction
	 *            the oAction to set
	 */
	public void setoAction(String oAction) {
		this.oAction = oAction;
	}

	public int doStartTag() {
		JspWriter out = pageContext.getOut();
		List<SelectTag> list = this.getData();
		SelectTag tag = null;
		StringBuffer select = new StringBuffer(100);
		String curr = "";
		for (int i = 0; i < list.size(); i++) {
			tag = list.get(i);
			try {
				if ("".equals(htmlValue)) {
					curr = tag.getTagDefault() == 1 ? "checked" : "";
				} else {
					if (tag.getTagValue().equals(htmlValue)) {
						curr = "checked";
					} else {
						curr = "";
					}
				}
				select.append("<input type='radio' class=\"inputRadio\" name=\"" + htmlId + "\" id=\"" + htmlId + i + "\" value=\""
						+ tag.getTagValue() + "\" " + curr + " "+ this.oAction +">\n");
				select.append("<label for=\"" + htmlId + i + "\">" + tag.getTagName() + "</label>");
			} catch (Exception e) {
				logger.error("初始化标签异常:" + this.tagId);
			}
		}
		try {
			out.print(select);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	/**
	 * 初始化数据
	 * 
	 * @return
	 */
	private List<SelectTag> getData() {
		SelectTagService service = (SelectTagService) DspUtil.getBean("selectTagService");
		DetachedCriteria dc = DetachedCriteria.forClass(SelectTag.class);
		dc.add(Restrictions.eq("tagId", this.tagId));
		dc.addOrder(Order.asc("tagValue"));
		return service.likeBy(dc);
	}

}
